package com.heima.wemedia.service.impl;

import com.heima.feign.clients.ScheduleClient;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.IWmNewsAutoScanService;
import com.heima.wemedia.service.IWmNewsToTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WmNewsToTaskService implements IWmNewsToTaskService {
    @Autowired
    private ScheduleClient scheduleClient;
    @Autowired
    private IWmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 文章发布审核----远程调用发布任务接口
     *
     * @param id
     * @param publishTime
     */
    @Override
    public void addNewsToTask(Integer id, Date publishTime) {
        //封装请求参数
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //参数封装到文章对象中进行序列化
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        //远程调用任务发布的服务
        scheduleClient.addTask(task);
    }

    /**
     * 定时执行
     * 远程调用拉取任务方法,执行文章审核
     */
    @Override
    @Scheduled(fixedRate = 30000) //每50秒自动执行
    public void autoTaskConsuming() {
        //远程调用发布任务
        Task task = null;
        try {
            task = scheduleClient.pollTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        } catch (Exception e) {
            throw new RuntimeException("暂无审核任务");
        }
        //判断任务是否存在
        if (task != null && task.getParameters().length>0) {
            //解析任务中的参数属性,获取到文章id
            byte[] bytes = task.getParameters();
            WmNews wmNews = ProtostuffUtil.deserialize(bytes, WmNews.class);
            //获取对象中的文章id
            Integer id = wmNews.getId();
            //调用文章审核服务
            wmNewsAutoScanService.AutoScanTextAndImages(id);
        }
    }
}
